package cn.mdmbct.spring.starter.douyin.data.config;


import cn.mdmbct.douyin.common.config.HttpConfig;
import cn.mdmbct.douyin.common.http.apache.ApacheHttpExecutorFactory;
import cn.mdmbct.douyin.common.http.okhttp.OkHttpExecutorFactory;
import cn.mdmbct.douyin.common.storage.DyStorageManager;
import cn.mdmbct.douyin.data.service.DyExternalDataServiceImpl;
import cn.mdmbct.douyin.data.service.interfaces.DyExternalDataService;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.DyOpenApiProperties;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.HttpProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/18 21:23
 * @modified mdmbct
 * @since 1.0
 */
@Configuration
public class DyOpenApiDataServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DyExternalDataService dyExternalDataService(DyOpenApiProperties apiProperties, DyStorageManager storageManager) {

        HttpProperties httpProperties = apiProperties.getHttp();
        HttpConfig httpConfig = new HttpConfig();
        BeanUtils.copyProperties(httpProperties, httpConfig);

        switch (httpProperties.getType()) {
            case OK_HTTP:
                return getDyExternalDataServiceWithOkHttp(httpConfig, storageManager);
            case APACHE_HTTP:
                return getDyExternalDataServiceWithApacheHttp(httpConfig, storageManager);
            default:
                return getDefaultDyExternalDataServiceImpl(httpConfig, storageManager);
        }
    }


    private DyExternalDataService getDyExternalDataServiceWithOkHttp(HttpConfig httpConfig, DyStorageManager storageManager) {

        return new DyExternalDataServiceImpl(storageManager, new OkHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyExternalDataService getDyExternalDataServiceWithApacheHttp(HttpConfig httpConfig, DyStorageManager storageManager) {
        return new DyExternalDataServiceImpl(storageManager, new ApacheHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyExternalDataService getDefaultDyExternalDataServiceImpl(HttpConfig httpConfig, DyStorageManager storageManager) {
        return getDyExternalDataServiceWithOkHttp(httpConfig, storageManager);
    }
}
